package com.beyond.core.service;

import com.beyond.core.codec.SettingRadarProtocol;
import com.beyond.core.handler.FaultQueryHandler;
import com.beyond.core.handler.ProofTimeHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;

/**
 * 程序启动主动故障查询
 * 描述：
 * @author shulei
 * @date 2021年7月16日
 *
 */

@Service
@Slf4j
public class SendFaultQueryService implements ApplicationRunner {
    @Value("${schedSendIP}")
    private String schedSendIP;

    @Value("${schedSendPort}")
    private Integer schedSendPort;

    private byte opType = (byte) 0x80;//操作类型
    private byte objectFlag = 0x09;//对象标识

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //封装数据
        byte[] dateByte = SettingRadarProtocol.sendCommand(opType, objectFlag);
        //发送故障问询数据包
        EventLoopGroup sendDate = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(sendDate)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new FaultQueryHandler());
            Channel ch = bootstrap.bind(0).sync().channel();
            ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(dateByte),
                    new InetSocketAddress(schedSendIP, schedSendPort))).sync();
        } catch (Exception e) {
            log.error("故障问询启动异常，异常信息：{}", e);
            e.printStackTrace();
        } finally {
            sendDate.shutdownGracefully();
        }
    }
}
